/*
 * @(#)XmlDomUtil.java
 *
 * Copyright 2012 by ShenY BIS, All rights reserved.
 */

package com.bis.framework.util.xmlConvert;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * XmlDomUtil
 * 
 * @author BIS 2012-12-24
 */
public class XmlDomUtil
{
    /**
     * Logger
     */
    private static final Logger logger = Logger.getLogger(XmlDomUtil.class);
    /**
     * reader
     */
    static SAXReader            reader = new SAXReader();

    /**
     * getRootElement
     * @Description:
     * @param xml
     * @return
     * @throws DocumentException
     */
    public static Element getRootElement(String xml) throws DocumentException
    {
        if (null == xml || "".equals(xml))
            return null;

        Document document = null;
        if (xml.indexOf("<root>") == -1)
        {
            String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><root>";
            String xmlFooter = "</root>";
            xml = xmlHeader + xml + xmlFooter;
        }
        logger.debug(xml);
        Reader reader1 = new InputStreamReader(new ByteArrayInputStream(xml.getBytes()));
        document = reader.read(reader1);
        return document.getRootElement();
    }

    /**
     * getXmlString
     * @Description:
     * @param xml
     * @return
     */
    public static String getXmlString(String xml)
    {
        if (null == xml || "".equals(xml))
        {
            logger.error("xml is null");
            return null;
        }
        String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><root>";
        String xmlFooter = "</root>";
        xml = xmlHeader + xml + xmlFooter;
        return xml;
    }
}
